#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2012 KT
#
# Author: Choonho Son <choonho.son@kt.com>
#

from cloudcfg.hpc.pbs import PBS
from cloudcfg.lib.cmd_ssh import cmd_ssh
from cloudcfg.lib.cmd_nfs import cmd_nfs
from cloudcfg.lib.cmd_nis import cmd_nis
from cloudcfg.lib.cmd_tcp import cmd_tcp
from cloudcfg.lib.cmd_xen import cmd_xen
from cloudcfg.lib.cmd_account import cmd_account

from optparse import OptionParser
__version__="1.0"

class Node(PBS):
	__cfg__ = "cfg/cloudcfg.hpc.pbs.node"
	def __init__(self, cfg={}):
		PBS.__init__(self, cfg)
		#self.updateConfig(cfg)

	def install(self):
		self.updateConfig(self.cfg)

		self.logger.debug("###########################################")
		self.logger.debug("Install HPC culster role:Compute Node")
		self.logger.debug("###########################################")
		try:
			self.logger.debug("Check xentools version")
			cmd = cmd_xen(self.logger)
			cmd.updateXentools()
		except:
			self.logger.debug("Failed to update Xentools")
			

		#TODO:
		# if automation, config account is not needed
                self.logger.debug("##################")
		self.logger.debug("Config account")
		self.logger.debug("##################")
		cmd = cmd_account(self.logger)
		params = self.getSectionParams('account')
		cmd.useradd(params)

		self.logger.debug("##################")		
		self.logger.debug("Config NFS Client")
		self.logger.debug("##################")
		p = self.getSectionParams('nfs')
		cmd = cmd_nfs(self.logger)
		mnt_params = {'server':p['server'], 'path':p['temp_export'], 'mnt_point':p['mnt_point']}
		check = {'ip':p['server'], 'port':2049}
		con = cmd_tcp(self.logger)
		trial = con.checkConnection(check, trial=10,interval=30)
		if trial == True:
			self.logger.debug("Mount NFS server")
			cmd.client_mount(mnt_params)
			cmd.copy(p['auth_key_src'],p['auth_key_dst'])
			cmd.copy(p['priv_key_src'],p['priv_key_dst'])
			cmd.chown(p['auth_key_dst'],p['account'],p['group'])
			cmd.chown(p['priv_key_dst'],p['account'],p['group'])
			cmd.client_umount(mnt_params)
			cmd.updateAutomaster(p)
			cmd.updateAutohome(p)
		else:
			self.logger.info("Manually mount NFS Server")
		
		
		self.logger.debug("######################")		
		self.logger.debug("Configure NIS Client")
		self.logger.debug("######################")				
		params = self.getSectionParams('nis')
		params['NISDOMAIN'] = self.config.get('common','domain')
		cmd = cmd_nis(self.logger)
		cmd.installPackage(params['package'])
		cmd.updateNISDOMAIN(params)
		cmd.updateYPCONF(params)
		cmd.updateNsswitch()
		
		cmd.service('ypbind','restart')
		cmd.service('autofs','restart')
		cmd.addService('ypbind')
		cmd.addService('autofs')
		
		self.logger.debug("Configure PBS Pro")


def install(cfg):
	inst = Node(cfg)
	inst.install()

if __name__ == "__main__":
	install({})
